import { PAGE_TYPE, COMPONENT_TYPES } from '@/common/const'
import { SCROLL_TRIGGER_TYPE_MAP } from '@/common/const-animates'
import { isHasOwnProperty } from '@/plugins/utils'

export const pageScrollTrigger = {
  created() {
    const data_ = {
      pageImgTotal: 0,
      loadedPageImgNum: 0
    };
    for(let key in data_) {
      this[key] = data_[key];
    }
  },
  methods: {
    loadedPageImgs(compData, isAddNum){
      if(compData.components && compData.components.length > 0) {
        _.forEach(compData.components, (compData_) => {
          this.loadedPageImgs(compData_, isAddNum);
        })
      }
      if(compData.cid == COMPONENT_TYPES.wb_img){
        if(isAddNum){
          if(compData.cid == COMPONENT_TYPES.wb_img){
            if(compData.commonAttr.url){
              this.pageImgTotal++;
            }
          }
        }
        if(isHasOwnProperty(compData.commonAttr, "isLoadedImg") && compData.commonAttr.isLoadedImg){
          this.loadedPageImgNum++;
        }
      }
    },
    setPageImgTotal(){
      _.forEach(this.currentPage.components, (compData) => {
        this.loadedPageImgs(compData, true);
      })
    },
    startScrollTRigger(){
      if(this.siteAttrs.pageType == PAGE_TYPE.long && _.size(this.animates.isScrollTriggerGsap) > 0){
        this.scrollTriggerCb = window.setInterval(() => {
          // _.forEach(this.currentPage.components, (compData) => {
          //   this.loadedPageImgs(compData, false);
          // })
          if(window.gsap && window.ScrollTrigger && this.loadedPageImgNum >= this.pageImgTotal){
            window.clearInterval(this.scrollTriggerCb);
            window.gsap.registerPlugin(window.ScrollTrigger);

            _.forEach(this.animates.scrollTriggerType, (scrollTriggerType) => {
              if(scrollTriggerType == SCROLL_TRIGGER_TYPE_MAP.compMoveToCenter){
                this.initMoveToCenterBgScrollTRigger(window.gsap, window.ScrollTrigger);
              }else if(scrollTriggerType == SCROLL_TRIGGER_TYPE_MAP.imgAndWordEase){
                this.initImgWordScrollTRigger(window.gsap, window.ScrollTrigger);
              }
            })

            //如果不延迟，多层背景就会出问题，估计是代码执行顺利的问题
            window.setTimeout(() => {
              _.forEach(this.currentPage.components, (compData) => {
                if(compData.components && compData.components.length > 0) {
                  let scrollTrigger = compData.commonAttr.scrollTrigger;
                  if(compData.commonAttr.isScrollTriggerGsap){
                    let scrollTriggerType = compData.commonAttr.scrollTriggerType;
                    if(scrollTriggerType == SCROLL_TRIGGER_TYPE_MAP.offsetGood){
                      this.initOffsetScrollTrigger(window.gsap, scrollTrigger.groupClassName, scrollTrigger.items);
                    }else if(scrollTriggerType == SCROLL_TRIGGER_TYPE_MAP.multiBg){
                      this.initMultiBgScrollTRigger(window.gsap, scrollTrigger.groupClassName);
                    }else if(scrollTriggerType ==  SCROLL_TRIGGER_TYPE_MAP.fixed){
                      this.initFixedScrollTRigger(window.gsap, scrollTrigger);
                    }
                  }
                }
              })
              window.ScrollTrigger.refresh();
            }, 200)

          }
        }, this.siteInfo.reloadTime)
      }
    },
    initImgWordScrollTRigger(gsap, ScrollTrigger){
      function animateFrom(elem, direction) {
        direction = direction | 1;
        
        let compData = this.componentMap[elem.id];
        let scrollTrigger = compData && compData.commonAttr.scrollTrigger;

        let x = 0,
            y = direction * scrollTrigger.offsetY ? scrollTrigger.offsetY : 100,
            offsetX = scrollTrigger.offsetX ? scrollTrigger.offsetX: 100;
        if(elem.classList.contains("scroll-trigger-img-word-animate-left")) {
          x = -offsetX;
          y = 0;
        } else if(elem.classList.contains("scroll-trigger-img-word-animate-right")) {
          x = offsetX;
          y = 0;
        }
        gsap.fromTo(elem, {x: x, y: y, autoAlpha: 0}, {
          duration: scrollTrigger.ease ? scrollTrigger.ease : 1.25,
          x: 0,
          y: 0, 
          autoAlpha: 1, 
          ease: scrollTrigger.ease ? scrollTrigger.ease : "expo", 
          overwrite: "auto"
        });
      }
      
      function hide(elem) {
        gsap.set(elem, {autoAlpha: 0});
      }

      gsap.utils.toArray(".scroll-trigger-img-word-animate").forEach(function(elem) {
        hide(elem); // assure that the element is hidden when scrolled into view
        
        ScrollTrigger.create({
          trigger: elem,
          onEnter: function() { animateFrom(elem) }, 
          onEnterBack: function() { animateFrom(elem, -1) },
          onLeave: function() { hide(elem) } // assure that the element is hidden when scrolled into view
        });
      });
      
    },
    initMoveToCenterBgScrollTRigger(gsap, ScrollTrigger){
      // const allPages = this.allPages;
      function animateFrom(elem, direction) {
        direction = direction | 1;

        let compData = this.componentMap[elem.id];
        let scrollTrigger = compData.commonAttr.scrollTrigger;

        let x = 0,
            y = direction * direction * scrollTrigger.offsetY ? scrollTrigger.offsetY : 100,
            offsetX = scrollTrigger.offsetX ? scrollTrigger.offsetX : 200;
        if(elem.classList.contains("scroll-trigger-move-to-center-animate-left")) {
          x = -offsetX;
          y = 0;
        } else if(elem.classList.contains("scroll-trigger-move-to-center-animate-right")) {
          x = offsetX;
          y = 0;
        }
        gsap.fromTo(elem, {x: x, y: y, autoAlpha: 0}, {
          duration: scrollTrigger.duration ? scrollTrigger.duration : 1.25, 
          x: 0,
          y: 0, 
          autoAlpha: 1, 
          ease: scrollTrigger.ease ? scrollTrigger.ease : "bounce", 
          overwrite: "auto"
        });
      }
      
      function hide(elem) {
        gsap.set(elem, {autoAlpha: 0});
      }

      gsap.utils.toArray(".scroll-trigger-move-to-center-animate").forEach(function(elem) {
        hide(elem); // assure that the element is hidden when scrolled into view
        
        ScrollTrigger.create({
          trigger: elem,
          onEnter: function() { animateFrom(elem) }, 
          onEnterBack: function() { animateFrom(elem, -1) },
          onLeave: function() { hide(elem) } // assure that the element is hidden when scrolled into view
        });
      });
    },
    initOffsetScrollTrigger(gsap, conClassName, items){
      let offsetGsap = gsap.timeline({
        scrollTrigger: {
          trigger: "." + conClassName,
          start: "center bottom",
          end: "top top",
          scrub: true
        }
      });
      _.forEach(items, (item) => {
        offsetGsap.to("." + item.className, { yPercent: item.yPercent }, 0)
      })
      // .to(".barrel", { yPercent:  45 }, 0)
      // .to(".spring", { yPercent: 170 }, 0)
      // .to(".slide",  { yPercent: -40 }, 0)
      // .to(".base",   { yPercent:  35 }, 0)
      // let xx = {"178e8892-81fb-4013-984c-3c40d5853512":{"yPercent":"-60"},"e009ba4d-7917-47ad-90af-994218e0b884":{"yPercent":"45"},"1e4c298f-14e2-4bf7-92e8-40fc9cefb45a":{"yPercent":"170"},"ef871eac-bde4-4b7b-b4bb-7966d3a43f0d":{"yPercent":"35"}}
      // var xx = {
      //   "178e8892-81fb-4013-984c-3c40d5853512":{"yPercent":"-40"},
      //   "e009ba4d-7917-47ad-90af-994218e0b884":{"yPercent":"45"},
      //   "1e4c298f-14e2-4bf7-92e8-40fc9cefb45a":{"yPercent":"170"},
      //   "ef871eac-bde4-4b7b-b4bb-7966d3a43f0d":{"yPercent":"35"}
      // }
    },
    initMultiBgScrollTRigger(gsap, conClassName){
      const totalScroll = document.documentElement.scrollHeight - document.documentElement.clientHeight;
      gsap.to("." + conClassName, {
        scrollTrigger: {
          scrub: true
        }, 
        y: (i, target) => -totalScroll * target.dataset.speed,
        ease: "none"
      });
    },
    initFixedScrollTRigger(gsap, scrollTrigger){
      let triggerDom = "." + scrollTrigger.groupClassName;
      if(!scrollTrigger.isPin){
        if(scrollTrigger.lineClassName){
          triggerDom = "." + scrollTrigger.lineClassName;
        }else{
          triggerDom = "." + scrollTrigger.conClassName;
        }
      }
      if(scrollTrigger.rotation || scrollTrigger.scaleX){
        let tl = gsap.timeline({
          scrollTrigger: {
            trigger: triggerDom,
            scrub: true,
            pin: scrollTrigger.isPin,
            start: scrollTrigger.start,//top top
            end: scrollTrigger.end,//+=100%
            toggleActions: "play none none none",
            // toggleActions: "restart pause resume pause",
            // toggleActions: "play complete reverse reset",
            // toggleActions: "play pause resume pause"
          }
        });
        tl.from("." + scrollTrigger.conClassName, {
          scale: scrollTrigger.scaleX, 
          rotation: scrollTrigger.rotation, 
          autoAlpha: 0, 
          ease: scrollTrigger.ease
        }, 0);
        if(scrollTrigger.lineClassName){
          tl.from("." + scrollTrigger.lineClassName, {
            scaleX: 0, 
            transformOrigin: "left center", 
            ease: "none"
          }, 0);
        }
      }else{
        gsap.from("." + scrollTrigger.lineClassName, {
          scrollTrigger: {
            trigger: triggerDom,
            scrub: true,
            pin: scrollTrigger.isPin,
            start: scrollTrigger.start,//top top
            end: scrollTrigger.end//+=100%
          },
          scaleX: scrollTrigger.scaleX,
          transformOrigin: "left center", 
          ease: scrollTrigger.ease,
        });
      }
    },
  },
}